import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';
import 'config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 根据配置决定是否在启动时请求权限
  if (AppConfig.autoRequestPermissions) {
    await _requestConfiguredPermissions();
  }
  
  runApp(const MyApp());
}

/// 根据配置申请权限
Future<void> _requestConfiguredPermissions() async {
  final config = AppConfig.permissionConfig;
  
  if (config.requestCamera) {
    await Permission.camera.request();
  }
  if (config.requestMicrophone) {
    await Permission.microphone.request();
  }
  if (config.requestLocation) {
    await Permission.location.request();
  }
  if (config.requestPhone) {
    await Permission.phone.request();
  }
  if (config.requestStorage) {
    await Permission.storage.request();
  }
  if (config.requestContacts) {
    await Permission.contacts.request();
  }
  if (config.requestNotification) {
    await Permission.notification.request();
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: AppConfig.appName,
      debugShowCheckedModeBanner: AppConfig.showDebugBanner,
      theme: ThemeData(
        primarySwatch: MaterialColor(AppConfig.primaryColor, {
          50: Color(AppConfig.primaryColor).withOpacity(0.1),
          100: Color(AppConfig.primaryColor).withOpacity(0.2),
          200: Color(AppConfig.primaryColor).withOpacity(0.3),
          300: Color(AppConfig.primaryColor).withOpacity(0.4),
          400: Color(AppConfig.primaryColor).withOpacity(0.5),
          500: Color(AppConfig.primaryColor),
          600: Color(AppConfig.primaryColor).withOpacity(0.7),
          700: Color(AppConfig.primaryColor).withOpacity(0.8),
          800: Color(AppConfig.primaryColor).withOpacity(0.9),
          900: Color(AppConfig.primaryColor).withOpacity(1.0),
        }),
      ),
      home: const WebViewPage(),
    );
  }
}

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});
  
  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  InAppWebViewController? _controller;
  bool _isLoading = true;
  double _progress = 0.0;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          title: Text(AppConfig.appName),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () async {
              final shouldPop = await _onWillPop();
              if (shouldPop && context.mounted) {
                Navigator.of(context).pop();
              }
            },
          ),
          actions: [
            // 调试功能按钮
            IconButton(
              icon: const Icon(Icons.security),
              onPressed: _testPermissions,
            ),
            IconButton(
              icon: const Icon(Icons.videocam),
              onPressed: _testWebViewMedia,
            ),
            IconButton(
              icon: const Icon(Icons.location_on),
              onPressed: _testGeolocation,
            ),
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                _controller?.reload();
              },
            ),
          ],
        ),
        body: Stack(
          children: [
            InAppWebView(
              initialUrlRequest: URLRequest(
                url: WebUri(AppConfig.homeUrl),
              ),
              initialSettings: InAppWebViewSettings(
                javaScriptEnabled: true,
                domStorageEnabled: true,
                databaseEnabled: true,
                userAgent: AppConfig.userAgent,
                mediaPlaybackRequiresUserGesture: false,
                allowsInlineMediaPlayback: true,
                // 启用摄像头和麦克风权限
                mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
                // 启用地理位置权限
                geolocationEnabled: true,
                // 允许WebView访问设备权限
                allowsBackForwardNavigationGestures: true,
              ),
              onWebViewCreated: (controller) {
                _controller = controller;
                debugPrint('🔧 WebView创建完成');
              },
              onLoadStart: (controller, url) {
                setState(() {
                  _isLoading = true;
                });
                debugPrint('🔄 开始加载: $url');
              },
              onLoadStop: (controller, url) {
                setState(() {
                  _isLoading = false;
                });
                debugPrint('✅ 加载完成: $url');
                _injectPermissionScript();
              },
              onProgressChanged: (controller, progress) {
                setState(() {
                  _progress = progress / 100;
                });
              },
              onReceivedError: (controller, request, error) {
                debugPrint('❌ WebView错误: ${error.description}');
              },
              // 🔥 关键：Android权限处理
              androidOnPermissionRequest: (controller, origin, resources) async {
                debugPrint('🔥 Android权限请求: $origin, 资源: $resources');
                
                // 检查和请求权限
                List<String> missingPermissions = [];
                bool shouldGrant = true;
                
                for (String resource in resources) {
                  if (resource == PermissionResourceType.CAMERA) {
                    final status = await Permission.camera.status;
                    if (!status.isGranted) {
                      final newStatus = await Permission.camera.request();
                      if (!newStatus.isGranted) {
                        shouldGrant = false;
                        missingPermissions.add('摄像头');
                      }
                    }
                  } else if (resource == PermissionResourceType.MICROPHONE) {
                    final status = await Permission.microphone.status;
                    if (!status.isGranted) {
                      final newStatus = await Permission.microphone.request();
                      if (!newStatus.isGranted) {
                        shouldGrant = false;
                        missingPermissions.add('麦克风');
                      }
                    }
                  }
                }
                
                if (shouldGrant) {
                  debugPrint('✅ 授权WebView访问: $resources');
                  return PermissionRequestResponse(
                    resources: resources,
                    action: PermissionRequestResponseAction.GRANT,
                  );
                } else {
                  debugPrint('❌ 拒绝WebView访问，缺少权限: $missingPermissions');
                  
                  // 显示权限提示对话框
                  if (mounted) {
                    _showPermissionDialog(missingPermissions);
                  }
                  
                  return PermissionRequestResponse(
                    resources: resources,
                    action: PermissionRequestResponseAction.DENY,
                  );
                }
              },
              onConsoleMessage: (controller, consoleMessage) {
                debugPrint('📱 WebView控制台: ${consoleMessage.message}');
              },
              // 🌍 地理位置权限处理
              androidOnGeolocationPermissionsShowPrompt: (controller, origin) async {
                debugPrint('🌍 地理位置权限请求: $origin');
                
                // 首先检查系统定位权限状态
                final status = await Permission.location.status;
                
                if (status.isGranted) {
                  debugPrint('✅ 系统定位权限已授权，允许WebView访问');
                  return GeolocationPermissionShowPromptResponse(
                    origin: origin,
                    allow: true,
                    retain: true,
                  );
                } else {
                  debugPrint('❌ 系统定位权限未授权，请求权限...');
                  
                  // 请求系统定位权限
                  final newStatus = await Permission.location.request();
                  
                  if (newStatus.isGranted) {
                    debugPrint('✅ 系统定位权限请求成功，允许WebView访问');
                    return GeolocationPermissionShowPromptResponse(
                      origin: origin,
                      allow: true,
                      retain: true,
                    );
                  } else {
                    debugPrint('❌ 系统定位权限请求失败');
                    
                    // 显示定位权限提示对话框
                    if (mounted) {
                      _showLocationPermissionDialog();
                    }
                    
                    return GeolocationPermissionShowPromptResponse(
                      origin: origin,
                      allow: false,
                      retain: false,
                    );
                  }
                }
              },
            ),
            if (_isLoading)
              Column(
                children: [
                  LinearProgressIndicator(value: _progress),
                  const Expanded(
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }

  /// 注入权限检查JavaScript脚本
  void _injectPermissionScript() {
    _controller?.evaluateJavascript(source: '''
      console.log('🔧 注入权限检查脚本');
      
      // 重写getUserMedia方法以添加更好的错误处理
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        const originalGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
        navigator.mediaDevices.getUserMedia = function(constraints) {
          console.log('📹 getUserMedia 被调用:', constraints);
          return originalGetUserMedia(constraints).then(stream => {
            console.log('✅ getUserMedia 成功');
            return stream;
          }).catch(error => {
            console.error('❌ getUserMedia 失败:', error);
            throw error;
          });
        };
      }
      
      // 添加权限状态检查函数
      window.checkPermissions = function() {
        if (navigator.permissions) {
          navigator.permissions.query({name: 'camera'}).then(result => {
            console.log('📷 摄像头权限状态:', result.state);
          });
          navigator.permissions.query({name: 'microphone'}).then(result => {
            console.log('🎤 麦克风权限状态:', result.state);
          });
          navigator.permissions.query({name: 'geolocation'}).then(result => {
            console.log('🌍 地理位置权限状态:', result.state);
          });
        }
      };
      
      // 重写地理位置API以添加更好的错误处理
      if (navigator.geolocation) {
        const originalGetCurrentPosition = navigator.geolocation.getCurrentPosition.bind(navigator.geolocation);
        const originalWatchPosition = navigator.geolocation.watchPosition.bind(navigator.geolocation);
        
        navigator.geolocation.getCurrentPosition = function(success, error, options) {
          console.log('🌍 getCurrentPosition 被调用');
          return originalGetCurrentPosition(success, error, options);
        };
        
        navigator.geolocation.watchPosition = function(success, error, options) {
          console.log('🌍 watchPosition 被调用');
          return originalWatchPosition(success, error, options);
        };
      }
      
      // 页面加载时检查权限
      window.checkPermissions();
    ''');
  }
  
  void _showPermissionDialog(List<String> missingPermissions) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppConfig.permissionDialogTitle),
        content: Text('需要以下权限才能正常使用：\n${missingPermissions.join('、')}\n\n${AppConfig.permissionDialogContent}'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(AppConfig.cancelText),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              openAppSettings();
            },
            child: Text(AppConfig.goToSettingsText),
          ),
        ],
      ),
    );
  }

  void _showLocationPermissionDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('定位权限'),
        content: const Text('应用需要定位权限才能为您提供位置服务。\n\n请在设置中开启定位权限。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(AppConfig.cancelText),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              openAppSettings();
            },
            child: Text(AppConfig.goToSettingsText),
          ),
        ],
      ),
    );
  }

  Future<void> _testPermissions() async {
    final config = AppConfig.permissionConfig;
    List<Widget> permissionWidgets = [];
    
    // 根据配置显示权限状态
    if (config.showCamera) {
      final status = await Permission.camera.status;
      permissionWidgets.add(
        Text('${AppConfig.cameraPermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showMicrophone) {
      final status = await Permission.microphone.status;
      permissionWidgets.add(
        Text('${AppConfig.microphonePermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showLocation) {
      final status = await Permission.location.status;
      permissionWidgets.add(
        Text('${AppConfig.locationPermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showPhone) {
      final status = await Permission.phone.status;
      permissionWidgets.add(
        Text('${AppConfig.phonePermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showStorage) {
      final status = await Permission.storage.status;
      permissionWidgets.add(
        Text('${AppConfig.storagePermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showContacts) {
      final status = await Permission.contacts.status;
      permissionWidgets.add(
        Text('${AppConfig.contactsPermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (config.showNotification) {
      final status = await Permission.notification.status;
      permissionWidgets.add(
        Text('${AppConfig.notificationPermissionName}: ${status.isGranted ? AppConfig.permissionGranted : AppConfig.permissionDenied}'),
      );
    }
    
    if (context.mounted) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(AppConfig.permissionStatusTitle),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: permissionWidgets,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text(AppConfig.confirmText),
            ),
          ],
        ),
      );
    }
  }

  Future<void> _testWebViewMedia() async {
    await _controller?.evaluateJavascript(source: '''
      console.log('🧪 测试WebView媒体权限...');
      
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
          .then(function(stream) {
            console.log('✅ 成功！');
            alert('✅ 摄像头和麦克风权限测试成功！\\n视频轨道: ' + stream.getVideoTracks().length + '\\n音频轨道: ' + stream.getAudioTracks().length);
            stream.getTracks().forEach(track => track.stop());
          })
          .catch(function(error) {
            console.log('❌ 失败:', error.name, error.message);
            alert('❌ 权限测试失败！\\n错误: ' + error.name + '\\n消息: ' + error.message);
          });
      } else {
        alert('❌ 此设备不支持getUserMedia API');
      }
    ''');
  }

  Future<void> _testGeolocation() async {
    await _controller?.evaluateJavascript(source: '''
      console.log('🧪 测试WebView地理位置权限...');
      
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          function(position) {
            console.log('✅ 定位成功!');
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            const accuracy = position.coords.accuracy;
            alert('✅ 定位权限测试成功！\\n纬度: ' + lat + '\\n经度: ' + lng + '\\n精度: ' + accuracy + '米');
          },
          function(error) {
            console.log('❌ 定位失败:', error.code, error.message);
            let errorMsg = '';
            switch(error.code) {
              case error.PERMISSION_DENIED:
                errorMsg = '用户拒绝了定位权限';
                break;
              case error.POSITION_UNAVAILABLE:
                errorMsg = '位置信息不可用';
                break;
              case error.TIMEOUT:
                errorMsg = '获取位置信息超时';
                break;
              default:
                errorMsg = '未知错误';
                break;
            }
            alert('❌ 定位权限测试失败！\\n错误码: ' + error.code + '\\n错误信息: ' + errorMsg);
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 60000
          }
        );
      } else {
        alert('❌ 此设备不支持地理位置API');
      }
    ''');
  }

  Future<bool> _onWillPop() async {
    // 检查是否可以后退
    if (await _controller?.canGoBack() ?? false) {
      // 如果可以后退，执行后退操作
      await _controller?.goBack();
      return false; // 不关闭应用
    }
    
    // 如果不能后退，显示确认对话框
    return await _showExitConfirmDialog() ?? false;
  }

  Future<bool?> _showExitConfirmDialog() async {
    return showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(AppConfig.exitDialogTitle),
          content: Text(AppConfig.exitDialogContent),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: Text(AppConfig.cancelText),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text(AppConfig.confirmText),
            ),
          ],
        );
      },
    );
  }
}
